package com.xiaozhengkeji.minecraft.plugin.fishplus.utils;



import com.comphenix.protocol.utility.StreamSerializer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.bukkit.inventory.ItemStack;


import java.util.LinkedList;
import java.util.List;

public class ItemUtils {
    public static ItemStack getItemStack(String data) {
        StreamSerializer ss = new StreamSerializer();
        try {
            return ss.deserializeItemStack(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toData(ItemStack item) {
        StreamSerializer ss = new StreamSerializer();
        try {
            return ss.serializeItemStack(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Item转Json
     */
    public static String itemToJson(ItemStack is) {
        if (is == null) {
            return "null";
        }
        return toData(is);
    }

    /**
     * Json转Item
     */
    public static ItemStack jsonToItem(String json) {
        if (json.equalsIgnoreCase("null")) {
            return null;
        }
        return getItemStack(json);
    }

    /**
     * Item集合转Json
     */
    public static String itemsToJson(List<ItemStack> is) {
        List<String> strings = new LinkedList<>();
        for (ItemStack itemStack : is) {
            strings.add(itemToJson(itemStack));
        }
        return new Gson().toJson(strings);
    }

    /**
     * Json转Item集合
     */
    public static List<ItemStack> jsonToItems(String json) {
        List<String> strings = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType());
        List<ItemStack> itemStacks = new LinkedList<>();
        for (String s : strings) {
            itemStacks.add(jsonToItem(s));
        }
        return itemStacks;
    }

    /**
     * []转list
     */
    public static List<ItemStack> itemToList(ItemStack[] itemStacks) {
        List<ItemStack> itemStackList = new LinkedList<>();
        for (ItemStack is : itemStacks) {
            itemStackList.add(is);
        }
        return itemStackList;
    }

    /**
     * list转[]
     */
    public static ItemStack[] itemToArr(List<ItemStack> itemStacks) {
        ItemStack[] itemStackss = new ItemStack[itemStacks.size()];
        return itemStacks.toArray(itemStackss);
    }

}
